/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */
import Util from '../libs/util'

window.axios = require('axios');

window.uploadHeaders = window.axios.defaults.headers.common = {
  'X-CSRF-TOKEN': window.Laravel.csrfToken,
  'X-Requested-With': 'XMLHttpRequest'
};
window.axios.defaults.baseUrl = window.Laravel.baseUrl;

/**
 * Handling Errors
 */
window.axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response;
}, function (error) {
  let response = error.response;
  if (response){
    switch (response.status) {
      case 401:
        Util.logout()
        break;
      case 422:
        if (response.data.errors){
          _.forOwn(response.data.errors, (item, key) => {
            app.$Notice.error({
              title: '数据不合法',
              desc: item[0]
            })
          })
        } else {
          _.forOwn(response.data, (item, key) => {
            app.$Notice.error({
              title: '数据不合法',
              desc: item
            })
          })
        }
        break;
      case 500:
      default:
        app.$Notice.error({
          title: '程序错误',
          desc: '请联系技术人员'
        });
        break;
    }
  } else {
    app.$Notice.error({
      title: '数据加载超时',
      desc: '请尝试刷新页面，并仔细检查网络链接状况或联系技术人员！'
    });
  }

  return Promise.reject(error);
});
